//
//  YYLOAuthViewController.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/3/28.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit
import SVProgressHUD
//微博的AppKey
let appkey = "2303189928"
//微博的密码
let client_secret = "5e3f3be3fdc80f3e6a5a32b448d2b332"
//微博的授权回调页
let redirect_uri = "http://www.itcast.cn"



class YYLOAuthViewController: UIViewController {

    private lazy var webView:UIWebView = UIWebView()
    //新建viewModel
    lazy var userAccountViewModel: YYLUserAccountViewModel = YYLUserAccountViewModel.shareViewModel
    
    override func loadView() {
        
        self.view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadNavItemView()
        setupUI()
    }
    func setupUI() {
       webView.backgroundColor = UIColor.white
        //设置UIWebView的代理
        webView.delegate = self
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(redirect_uri)")
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        
    }
    
    private func loadNavItemView() {
        //直接调用自己封装的分来方法来获取UIBarButtonItem
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        navigationItem.title = "微博登录"
    }

    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: nil)
    
    }
    
    @objc private func autoFillAction() {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18010012404';")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('passwd').value = 'yyl06252';")
    }
    
//    //通过code获取token
//    fileprivate func requestAccessToken(code: String) {
//        
//        YYLNetTools.sharedTools.requestaccessToken(code: code) { (response, error) in
//            if error != nil {
//                print("获取token时网络请求失败，\(error)")
//                return
//            }
//            //到这里表示请求成功
//            guard let dic = response as? [String: Any] else {
//                print("服务器给的格式不对")
//                return
//            }
//            //表示数据格式正确   把字典转模型
//            var userAccount: YYLUserAccount?
//            
//            userAccount = YYLUserAccount.init(dic: dic)
//            
//            //通过token和uid获取用户信息
//            self.requestUserInfo(userAccount: userAccount!)
//        }
//
//    }
//    
//    //通过token和uid获取用户信息
//    fileprivate func requestUserInfo(userAccount: YYLUserAccount) {
//    
//        let token = userAccount.access_token!
//        let uid = userAccount.uid
//        
//        YYLNetTools.sharedTools.requestUserInfo(access_token: token, uid: uid) { (response, error) in
//            if error != nil {
//                print("获取用户信息时网络请求失败，\(error)")
//                return
//            }
//            //到这里表示请求成功
//            guard let dic = response as? [String: Any] else {
//                print("服务器给的格式不对")
//                return
//            }
//            //到这里表示数据类型正常
//            let name = dic["name"] as! String
//            let avatar_large = dic["avatar_large"] as! String
//            
//            userAccount.name = name
//            userAccount.avatar_large = avatar_large
//            
//            userAccount.saveUserAccount()
//        }
//    
//    
//    }
    
}

//MARK:UIWebView的代理的具体实现
extension YYLOAuthViewController: UIWebViewDelegate {

    //  开始加载之前获取code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlStr = request.url?.absoluteString else {
            //地址为nil
            return false
        }
        
        //代码到这里表示urlStr有值
        //urlStr里面没有授权回调页的地址
        if !urlStr.hasPrefix(redirect_uri) {
        return true
        }
        
        //代码执行到这里 表示是我们关心的   query表示请求的参数
        if let qurey = request.url?.query, qurey.hasPrefix("code=") {

        let code = qurey.substring(from: "code=".endIndex)
//            print(code)
            
            //通过code获取token
            userAccountViewModel.requestAccessToken(code: code, callBack: { (isSuccuss) in
                if isSuccuss {
                print("登录成功.当前消失 弹出欢迎")
                    self.dismiss(animated: false, completion: {
                        //发送通知
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootVCNotification), object: self)
                    })
                    
                    
                } else {
                print("登录失败")
                }
            })
    
        } else {
        //取消授权
            dismiss(animated: true, completion: {
            print("取消授权")
              SVProgressHUD.dismiss()
            })
        }
        

        return false
    }
    //  开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
}
